package com.nearby.demand.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.Direct;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.nearby.demand.R;
import com.nearby.demand.application.Constant;
import com.nearby.demand.ui.UiChat;
import com.nearby.demand.utils.KLog;
import com.nearby.demand.voice.VoicePlayClickListener;

import java.util.List;

/**
 * Created by lizhangqu on 2015/6/home_3.
 */
public class MessageAdapter extends BaseRecyclerViewAdapter<EMMessage, MessageAdapter.MessageViewHolder> {

    private static final int MESSAGE_TYPE_RECV_TXT = 0;//接收文本
    private static final int MESSAGE_TYPE_SENT_TXT = 1;//发送文本


    private static final int MESSAGE_TYPE_RECV_IMAGE = 5;//接收图片
    private static final int MESSAGE_TYPE_SENT_IMAGE = 2; //发送图片


    private static final int MESSAGE_TYPE_SENT_LOCATION = 3;//发送位置
    private static final int MESSAGE_TYPE_RECV_LOCATION = 4;//接收位置


    private static final int MESSAGE_TYPE_SENT_VOICE = 6; //发送语音
    private static final int MESSAGE_TYPE_RECV_VOICE = 7;//接收语音


    private static final int MESSAGE_TYPE_SENT_VIDEO = 8;//发送视频
    private static final int MESSAGE_TYPE_RECV_VIDEO = 9;//接收视频


    private static final int MESSAGE_TYPE_SENT_FILE = 10;//发送文件
    private static final int MESSAGE_TYPE_RECV_FILE = 11;//接收文件


    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 12;//语音通话发送
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 13;//语音通话接收


    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 14;//视频通话发送
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 15;//视频通话接收


    private static final int MESSAGE_TYPE_SENT_ROBOT_MENU = 16;//
    private static final int MESSAGE_TYPE_RECV_ROBOT_MENU = 17;//

    private String username;


    public MessageAdapter(List<EMMessage> messages, String username, Context context) {
        super(messages);
        this.username = username;
        activity = (Activity) context;

    }


    public void handleTextMessage(MessageViewHolder messageViewHolder, EMMessage message) {
        TextMessageBody txtBody = (TextMessageBody) message.getBody();
        String value = txtBody.getMessage();
        KLog.i("not - null" + value);
        if (null != value) {
            KLog.i("not - null");
            messageViewHolder.setText(R.id.tv_chat_content, value);
        } else {
            KLog.i("is - null");
        }
        if (message.direct == EMMessage.Direct.SEND) {
            KLog.i("is - SEND");
            switch (message.status) {
                case SUCCESS: // 发送成功

                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.GONE);
                    messageViewHolder.getView(R.id.msg_status).setVisibility(View.GONE);

                    break;
                case FAIL: // 发送失败


                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.GONE);
                    messageViewHolder.getView(R.id.msg_status).setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS: // 发送中
                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.VISIBLE);
                    messageViewHolder.getView(R.id.msg_status).setVisibility(View.GONE);
                    break;
                default:
                    // 发送消息
                    sendMsgInBackground(messageViewHolder, message);
            }
        }
    }

    public void handleVoiceMessage(final MessageViewHolder messageViewHolder, EMMessage message) {
        VoiceMessageBody voiceBody = (VoiceMessageBody) message.getBody();

        if (voiceBody != null) {
            messageViewHolder.setText(R.id.tv_length, voiceBody.getLength() + "\"");
            messageViewHolder.getView(R.id.iv_voice).setOnClickListener(new VoicePlayClickListener(
                    message,
                    (ImageView) messageViewHolder.getView(R.id.iv_voice),
                    (ImageView) messageViewHolder.getView(R.id.iv_unread_voice), this, activity, username));
            if (((UiChat) activity).playMsgId != null && ((UiChat) activity).playMsgId.equals(message
                    .getMsgId()) && VoicePlayClickListener.isPlaying) {
                AnimationDrawable voiceAnimation;
                if (message.direct == EMMessage.Direct.RECEIVE) {
                    messageViewHolder.setImageResource(R.id.iv_voice, R.anim.voice_from_icon);
                } else {
                    messageViewHolder.setImageResource(R.id.iv_voice, R.anim.voice_to_icon);
                }
                ImageView imageView = messageViewHolder.getView(R.id.iv_voice);
                voiceAnimation = (AnimationDrawable) imageView.getDrawable();
                voiceAnimation.start();
            } else {
                if (message.direct == EMMessage.Direct.RECEIVE) {
                    messageViewHolder.setImageResource(R.id.iv_voice, R.drawable.chatfrom_voice_playing);
                } else {
                    messageViewHolder.setImageResource(R.id.iv_voice, R.drawable.chatto_voice_playing);
                }
            }
            if (message.direct == EMMessage.Direct.RECEIVE) {
                if (message.isListened()) {
                    // 隐藏语音未听标志
                    messageViewHolder.getView(R.id.iv_unread_voice).setVisibility(View.INVISIBLE);
                } else {
                    messageViewHolder.getView(R.id.iv_unread_voice).setVisibility(View.VISIBLE);
                }
                System.err.println("it is receive msg");
                if (message.status == EMMessage.Status.INPROGRESS) {
                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.VISIBLE);
                    System.err.println("!!!! back receive");
                    ((FileMessageBody) message.getBody())
                            .setDownloadCallback(new EMCallBack() {

                                @Override
                                public void onSuccess() {
                                    activity.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            messageViewHolder.getView(R.id.pb_sending).setVisibility(View.INVISIBLE);
                                            notifyDataSetChanged();
                                        }
                                    });

                                }

                                @Override
                                public void onProgress(int progress, String status) {
                                }

                                @Override
                                public void onError(int code, String message) {
                                    activity.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            messageViewHolder.getView(R.id.pb_sending).setVisibility(View.INVISIBLE);
                                        }
                                    });

                                }
                            });

                } else {
                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.INVISIBLE);
                }
                return;
            }
            // until here, deal with send voice msg
            switch (message.status) {
                case SUCCESS:
                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.GONE);
                    messageViewHolder.getView(R.id.msg_status).setVisibility(View.GONE);
                    break;
                case FAIL:
                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.GONE);
                    messageViewHolder.getView(R.id.msg_status).setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS:
                    messageViewHolder.getView(R.id.pb_sending).setVisibility(View.VISIBLE);
                    messageViewHolder.getView(R.id.msg_status).setVisibility(View.GONE);

                    break;
                default:
                    sendMsgInBackground(messageViewHolder, message);
            }
        }

    }

    @Override
    protected void bindDataToItemView(MessageViewHolder myViewHolder, EMMessage message) {
        switch (message.getType()) {
            case IMAGE: // 图片
                break;
            case TXT: // 文本
                handleTextMessage(myViewHolder, message);
                break;
            case LOCATION: // 位置
                //                handleLocationMessage(message, holder, position, convertView);
                break;
            case VOICE: // 语音
                handleVoiceMessage(myViewHolder, message);

                break;
            case VIDEO: // 视频
                //                handleVideoMessage(message, holder, position, convertView);
                break;
            case FILE: // 一般文件
                //                handleFileMessage(message, holder, position, convertView);
                break;
            default:
                // not supported
        }
    }

    /**
     * 发送消息
     *
     * @param message
     * @param
     */
    public void sendMsgInBackground(MessageViewHolder messageViewHolder, final EMMessage message) {
        messageViewHolder.getView(R.id.msg_status).setVisibility(View.GONE);
        messageViewHolder.getView(R.id.pb_sending).setVisibility(View.VISIBLE);
        final long start = System.currentTimeMillis();
        // 调用sdk发送异步发送方法
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {

            @Override
            public void onSuccess() {
                KLog.i("发送...onSuccess");
                //                updateSendedView(message, holder);
            }

            @Override
            public void onError(int code, String error) {
                KLog.i("发送...onError");
                //                updateSendedView(message, holder);
            }

            @Override
            public void onProgress(int progress, String status) {
                KLog.i("发送...onProgress");
            }

        });

    }

    @Override //获取item类型
    public int getItemViewType(int position) {
        EMMessage message = getItem(position);
        int direct = -1;
        //判断显示图片类型 home_1.显示接收 0.显示发送
        switch (message.getType()) {
            case LOCATION:
                if (message.direct == Direct.RECEIVE) {
                    direct = 1;
                } else {
                    direct = 9;
                }
                //                return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_location, null) : inflater.inflate(
                //                        R.layout.row_sent_location, null);
                break;

            case IMAGE:
                if (message.direct == Direct.RECEIVE) {
                    direct = 1;
                } else {
                    direct = 9;
                }
                //                return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_picture, null) : inflater.inflate(
                //                        R.layout.row_sent_picture, null);
                break;


            case VOICE:
                if (message.direct == Direct.RECEIVE) {
                    direct = 1;
                } else {
                    direct = 9;
                }
                //                return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_voice, null) : inflater.inflate(
                //                        R.layout.row_sent_voice, null);
                break;
            case VIDEO:
                if (message.direct == Direct.RECEIVE) {
                    direct = 1;
                } else {
                    direct = 9;
                }
                //                return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_video, null) : inflater.inflate(
                //                        R.layout.row_sent_video, null);
                break;
            case FILE:
                if (message.direct == Direct.RECEIVE) {
                    direct = 1;
                } else {
                    direct = 9;
                }

                //                return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_file, null) : inflater.inflate(
                //                        R.layout.row_sent_file, null);
                break;
            default:
                // 语音通话
                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
                    if (message.direct == Direct.RECEIVE) {
                        direct = 1;
                    } else {
                        direct = 9;
                    }
                    //                    return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_voice_call, null) : inflater
                    //                            .inflate(R.layout.row_sent_voice_call, null);
                }// 视频通话
                else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    if (message.direct == Direct.RECEIVE) {
                        direct = 1;
                    } else {
                        direct = 9;
                    }
                    //                    return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_video_call,
                    //                            null) : inflater.inflate(R.layout.row_sent_video_call, null);
                }
                // 含有菜单的消息
                //                else if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message))
                //                    return message.direct == Direct.RECEIVE ? inflater.inflate(R.layout.row_received_menu, null)
                //                            : inflater.inflate(R.layout.row_sent_message, null);
                else {
                    if (message.direct == Direct.RECEIVE) {
                        direct = 1;
                    } else {
                        direct = 9;
                    }
                    //                    return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_message,
                    //                            null) : inflater.inflate(R.layout.row_sent_message, null);//接收与发送
                }

        }
        StringBuffer sb = new StringBuffer();
        sb.append(direct);
        //判断item类型
        if (message == null) {
            return -1;
        }
        if (message.getType() == EMMessage.Type.TXT) {

            if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {    // 语音通话
                if (message.direct == Direct.RECEIVE) {
                    sb.append(MESSAGE_TYPE_RECV_VOICE_CALL);
                    return Integer.valueOf(sb.toString());
                } else {
                    sb.append(MESSAGE_TYPE_SENT_VOICE_CALL);
                    return Integer.valueOf(sb.toString());
                }
                //                return message.direct == Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
            } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                // 视频通话
                if (message.direct == Direct.RECEIVE) {
                    sb.append(MESSAGE_TYPE_RECV_VIDEO_CALL);
                    return Integer.valueOf(sb.toString());
                } else {
                    sb.append(MESSAGE_TYPE_SENT_VIDEO_CALL);
                    return Integer.valueOf(sb.toString());
                }
                //                return message.direct == Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
            }

            //            else if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message)){// 含有菜单的消息
            //                return message.direct == Direct.RECEIVE ? MESSAGE_TYPE_RECV_ROBOT_MENU : MESSAGE_TYPE_SENT_ROBOT_MENU;
            //            }
            else {
                if (message.direct == Direct.RECEIVE) {
                    sb.append(MESSAGE_TYPE_RECV_TXT);
                    return Integer.valueOf(sb.toString());
                } else {
                    sb.append(MESSAGE_TYPE_SENT_TXT);
                    return Integer.valueOf(sb.toString());
                }
                //                return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
            }


        }
        if (message.getType() == EMMessage.Type.IMAGE) {
            if (message.direct == Direct.RECEIVE) {
                sb.append(MESSAGE_TYPE_RECV_IMAGE);
                return Integer.valueOf(sb.toString());
            } else {
                sb.append(MESSAGE_TYPE_SENT_IMAGE);
                return Integer.valueOf(sb.toString());
            }
            //            return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_IMAGE : MESSAGE_TYPE_SENT_IMAGE;

        }
        if (message.getType() == EMMessage.Type.LOCATION) {
            if (message.direct == Direct.RECEIVE) {
                sb.append(MESSAGE_TYPE_RECV_LOCATION);
                return Integer.valueOf(sb.toString());
            } else {
                sb.append(MESSAGE_TYPE_SENT_LOCATION);
                return Integer.valueOf(sb.toString());
            }
            //            return message.direct == Direct.RECEIVE ? MESSAGE_TYPE_RECV_LOCATION : MESSAGE_TYPE_SENT_LOCATION;
        }
        if (message.getType() == EMMessage.Type.VOICE) {
            if (message.direct == Direct.RECEIVE) {
                sb.append(MESSAGE_TYPE_RECV_VOICE);
                return Integer.valueOf(sb.toString());
            } else {
                sb.append(MESSAGE_TYPE_SENT_VOICE);
                return Integer.valueOf(sb.toString());
            }
            //            return message.direct == Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE : MESSAGE_TYPE_SENT_VOICE;
        }
        if (message.getType() == EMMessage.Type.VIDEO) {
            if (message.direct == Direct.RECEIVE) {
                sb.append(MESSAGE_TYPE_RECV_VIDEO);
                return Integer.valueOf(sb.toString());
            } else {
                sb.append(MESSAGE_TYPE_SENT_VIDEO);
                return Integer.valueOf(sb.toString());
            }
            //            return message.direct == Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO : MESSAGE_TYPE_SENT_VIDEO;
        }
        if (message.getType() == EMMessage.Type.FILE) {
            if (message.direct == Direct.RECEIVE) {
                sb.append(MESSAGE_TYPE_RECV_FILE);
                return Integer.valueOf(sb.toString());
            } else {
                sb.append(MESSAGE_TYPE_SENT_FILE);
                return Integer.valueOf(sb.toString());
            }
            //            return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_FILE : MESSAGE_TYPE_SENT_FILE;
        }

        return -1;// invalid
    }

    @Override
    public MessageViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
        KLog.i("type=" + type);
        if (type == 14) {//位置接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_location));
        } else if (type == 93) {//位置发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_location));
        } else if (type == 15) {//图片接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_picture));
        } else if (type == 92) {//图片发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_picture));
        } else if (type == 17) {//语音接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_voice));
        } else if (type == 96) {//语音发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_voice));
        } else if (type == 19) {//视频接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_video));
        } else if (type == 98) {//视频发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_video));
        } else if (type == 111) {//文件接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_file));
        } else if (type == 910) {//文件发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_file));
        } else if (type == 113) {//语音通话接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_voice_call));
        } else if (type == 912) {//语音通话发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_voice_call));
        } else if (type == 115) {//视频通话接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_video_call));
        } else if (type == 914) {//视频通话发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_video_call));
        } else if (type == 10) {//文本接收
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_received_message));
        } else if (type == 91) {//文本发送
            return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_sent_message));
        }
        return new MessageViewHolder(inflateItemView(viewGroup, R.layout.row_no));
    }

    public class MessageViewHolder extends BaseRecyclerViewAdapter.SparseArrayViewHolder {

        public MessageViewHolder(View itemView) {
            super(itemView);
        }
    }

}
